package com.exampl.common;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

//@ControllerAdvice(annotations = {Controller.class, RestController.class})
//@ResponseBody  // 由于传递的数据需转换为json数据
@RestControllerAdvice  // 包含上面两个注解
public class GlobalException {

    // 当出现相同时拦截
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandle(SQLIntegrityConstraintViolationException e){
        if(e.getMessage().contains("Duplicate")){
            String[] split = e.getMessage().split(" ");
            String err = split[2] + "   已存在";
            return R.error(err);
        }
        return R.error("未知错误！");
    }

    // 当出现无法删除时拦截
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandle1(CustomException e){
        return R.error(e.getMessage());
    }
}
